import { observable, action } from 'mobx';
import { Form, RouteLayout, MapPage } from 'weaver-mobile-page';
import * as adapter from '../../constants/adapter';
import { Tools, Modal, Bubble } from 'weaver-mobile';
import * as Apis from "../../api/customerApis";
const alert = Modal.alert;
const getLabel = Tools.getLabel;
const getCurrentPosition = MapPage.getCurrentPosition;
const addressTemp = ['country', 'province', 'city', 'district'];
const addressNumbers = {
    'country': 258,
    'province': 2222,
    'city': 58,
    'district': 263
}

export default class CustomerAddExistStore extends RouteLayout.Store {
    @observable form = {};//搜索表单
    @observable buttonProps = {};
    @observable showGoOn = false;
    @observable existList = [];
    @observable tooManyRecord = false;
    @observable noRecord = false;
    @observable showAddForm = false;
    @observable addForm = {};//新建表单
    @observable props;
    @observable saveContacter = false;
    @observable showMap = false;
    @observable complete = false;
    @observable addFormComplete = false;
    @observable getMapLayout = {};
    @observable getMap = {};
    @observable changeLocalLayout = {};
    //获取当前位置
    @observable location = "";
    //最终选取的位置
    @observable lat = 0;
    @observable lng = 0;
    // @observable position = "";
    @observable crmCard = {};
    @observable currentPath = "";
    @observable customerId = "";
    @observable contacterForm = {};
    @observable crm_name_duplication = 'N';
    @observable repeatCount = 0;


    @action
    initForm(props) {

        const currentPath = props.location.pathname;
        this.currentPath = currentPath;
        this.form = new Form.Store({ route: this.currentPath })
        this.props = props;
        this.clearAddForm();
        Tools.callApi({
            url: '/api/crm/mobile/getCustomerAddExist',
        }).then((res) => {
            this.crm_name_duplication = res.crm_name_duplication;
            this.form.initForm(res.datas, this.currentPath);
            this.complete = true;
            this.getMap = new MapPage.Store({ route: this.currentPath });
            this.getMapLayout = new RouteLayout.Store({ route: this.currentPath });
            this.crmCard = new RouteLayout.Store({ route: this.currentPath, id: 'crmCard' });
            this.contacterForm = new RouteLayout.Store({ route: this.currentPath, id: 'contacterForm' });
        });
    }

    @action
    searchHandle = (isContinue) => {
        if (this.form.doValidate().pass) {
            const type = this.form.formParams.type;
            const name = this.form.formParams.name;
            //搜索
            Tools.callApi({
                url: '/api/crm/customer/myCustomerListForAdd?type=' + type + '&name=' + name,
            }).then((res) => {
                this.tooManyRecord = res.tooManyRecord;
                this.noRecord = res.noRecord;
                this.existList = res.datas;
                this.buttonProps.loading = false;
                this.buttonProps.disabled = false;
                this.repeatCount = res.repeatCount;
                if (res.status === "failed") {
                    alert('', res.msgcode, [
                        { text: 'Ok', onPress: () => { } },
                    ])
                } else {
                    if (res.noRecord) {
                        this.buttonProps.content = getLabel('615', '提交');
                        this.buttonProps.clickType = "save";
                        this.showGoOn = false;
                        this.initAddForm();
                    }
                    if (res.tooManyRecord) {
                        this.buttonProps.clickType = "search";
                    }
                    if (!res.noRecord && !res.tooManyRecord) {
                        this.showGoOn = true;
                    }
                    // 如果点击的是继续
                    if (isContinue) {
                        if (this.repeatCount > 0 && this.crm_name_duplication == "N") {
                            Bubble.error(getLabel(512825, "该客户已存在，请重新输入！"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {

                            });
                        } else {
                            //新建
                            this.buttonProps.content = getLabel('615', '提交');
                            this.buttonProps.clickType = "save";
                            this.buttonProps.loading = false;
                            this.buttonProps.disabled = false;
                            this.showGoOn = false;
                            this.initAddForm();
                        }
                    }
                }
            });
        } else {
            this.buttonProps.loading = false;
            this.buttonProps.disabled = false;
        }
    }

    @action
    buttonClick = (clickType) => {
        this.buttonProps.loading = true;
        this.buttonProps.disabled = true;

        if (clickType === "cancel") {
            this.clearAddForm();
        } else if (clickType === "search") {
            this.searchHandle(false);
        } else if (clickType === "add") {
            this.searchHandle(true);
        } else if (clickType === "save") {
            if (this.addForm.doValidate().pass) {
                const params = { ...this.addForm.formParams, location: this.location };
                //保存
                Tools.callApi({
                    url: '/api/crm/customer/customerSave',
                    params: params,
                    method: 'POST'
                }).then((res) => {
                    if (res.status === 'success') {
                        window.crmGlobal && window.crmGlobal.doSearch();
                        if (this.saveContacter) {
                            this.customerId = res.datas;
                            let url = '/customerCard/' + res.datas;
                            // this.crmCard = new RouteLayout.Store({ route: this.currentPath, id: "crmCard"});
                            Bubble.success(
                                getLabel('83551', "保存成功"),
                                1,
                                { backgroundColor: adapter.BUBBLE_BGCOLOR },
                                2,
                                () => this.props.history.replace(this.crmCard.path)
                            );
                            setTimeout(() => {
                                //this.props.history.push(`/contacterForm/${res.datas}/add/customerCard`);
                                this.props.history.push(this.contacterForm.path);

                            }, 1000);
                        } else {
                            Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => this.props.history.go(-1));
                        }
                    } else {
                        Bubble.error(res.msgcode, 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
                            this.buttonProps.loading = false;
                            this.buttonProps.disabled = false;
                        });
                    }
                })
            } else {
                this.buttonProps.loading = false;
                this.buttonProps.disabled = false;
            }
        }
    }

    @action
    initAddForm = () => {
        this.showAddForm = true;
        this.addForm = new Form.Store({ route: this.currentPath });
        const type = this.form.formParams.type;
        const name = this.form.formParams.name;
        Tools.callApi({
            url: '/api/crm/customer/customerAdd?type=' + type + '&name=' + name,
        }).then((res) => {
            this.addForm.initForm(res.datas.customerInfo, this.currentPath);

            const countryStore = this.addForm.browsers.country;
            const provinceStroe = this.addForm.browsers.province;
            const cityStore = this.addForm.browsers.city;
            const districtStore = this.addForm.browsers.district;

            let  countryStoreIsNotdeFined = typeof(countryStore) != "undefined";
            let  provinceStroeIsNotdeFined = typeof(provinceStroe) != "undefined";
            let  cityStoreIsNotdeFined = typeof(cityStore) != "undefined";
            let  districtIsNotdeFined = typeof(districtStore) != "undefined";


            const newGetDatas = (store) => {

                if(typeof(store) == "undefined"){
                    return;
                }
                const getDatas = store.getDatas;
                const callApiFun = store.callApiFun;

                store.callApiFun = (url, params, callback) => {
                    const _this = this;
                    const cb = (...args) => {
                        callback(...args);
                        window.__setValue && window.__setValue(_this);
                    }
                    callApiFun(url, params, cb);
                };

                store.getDatas = function (params = {}, type) {
                    if (params.params && params.params.id == -1) {
                        this.loading = false;
                        return;
                    }
                    getDatas(params, type);
                };

            };
            newGetDatas(countryStore);
            newGetDatas(provinceStroe);
            newGetDatas(cityStore);
            newGetDatas(districtStore);

            if(countryStoreIsNotdeFined){
                countryStore.doClear = () => {};
            }
            if(provinceStroeIsNotdeFined){
                provinceStroe.doClear = () => {};
            }
            if(cityStoreIsNotdeFined){
                cityStore.doClear = () => {};
            }
            if(districtIsNotdeFined){
                districtStore.doClear = () => {};
            }

            this.addForm.updateFields(this.form.formData);
            this.addFormComplete = true;
            this.changeLocalLayout = new RouteLayout.Store({ route: this.currentPath, id: 'changeLocalLayout' });
        });
    }

    @action
    isSaveContacter = (bl) => {
        this.saveContacter = bl;
    }

    clearAddForm = () => {
        this.showAddForm = false;
        this.showGoOn = false;
        this.existList = [];
        this.tooManyRecord = false;
        this.noRecord = false;
        this.addForm = {};
        this.buttonProps = { loading: false, disabled: false, content: getLabel('197', "搜索"), clickType: "search" };
        this.complete = false
        this.addFormComplete = false;
        this.saveContacter = false;
        this.location = "";
        // this.position = "";
    }
    @action
    getLocation = (data) => {
        // console.log(data);
        //地址
        let address1 = data.address + data.name;
        //省
        let province = "";
        //市
        let city = "";
        //县
        let district = "";

        this.lat = data.location.split(",")[1] == ""?0:parseFloat(data.location.split(",")[1]);
        this.lng = data.location.split(",")[0] == ""?0:parseFloat(data.location.split(",")[0]);
        Tools.callApi(
            {
                url: 'https://restapi.amap.com/v3/geocode/regeo',
                method: 'GET',
                params: {
                    key: "deee9801361e46e9340bd492ae45b90d",
                    location: data.location,
                },
                includeCredentials: false,
            }
        ).then(data => {
            // console.log(data);
            if (data.status == '1') {
                province = data.regeocode.addressComponent.province;
                city = data.regeocode.addressComponent.city;
                district = data.regeocode.addressComponent.district;
                //address1 = (province ? province : "") + (city ? city : "") + (district ? district : "") + address1;
                //以下两个是浏览按钮，特殊处理
                //根据城市名称获取城市id,区县id
                Apis.GetCityId({ district: district, city: city ,customerId: this.customerId, lat: this.lat, lng: this.lng}).then(datas => {
                    if (datas.status === "success") {
                        const updateCity = [{ id: datas.cityid, name: city }];
                        const updateDistrict = [{ id: datas.districtid, name: district }];
                        this.addForm.updateField("city", updateCity);
                        this.addForm.updateField("district", updateDistrict);
                    }
                });
            }
            this.location = data.location;
            this.addForm.updateField("address1", address1);
        })
    }
    @action
    getCurrentPosition1 = (result) => {
        if (typeof (result) !== "undefined") {
            this.lng = result.position[0]==""?0:parseFloat(result.position[0]);
            this.lat = result.position[1]==""?0:parseFloat(result.position[1]);
            this.showMap = true;
        }
    }
    @action
    groupToggle = (...arg) => {
        const title = arg[0];
        const status = arg[1];
        this.addForm.conditioninfo = this.addForm.conditioninfo.map(c => ({
            ...c,
            ...(c.title === title ? { show: status } : {}),
        }));
    }

    @action
    setAddressInfo = (type, value) => {
        const v = value.length > 0 ? value[0].id : '';
        if (addressTemp.indexOf(type) > -1) {
            if(!value || value.length <= 0) {
                switch(type) {
                    case 'country': 
                        this.counS = '';
                        break;
                    case 'province':
                        this.provS = '';
                        break;
                    case 'city':
                        this.cityS = '';
                    case 'district':
                        this.districtS = '';
                }
            }

            switch (type) {
                case 'country':
                    if (!v || v !== this.counS) {
                        this.provS = '';
                        this.cityS = '';
                        this.districtS = '';
                    }
                    break;
                case 'province':
                    if (!v || v !== this.provS) {
                        this.cityS = '';
                        this.districtS = '';
                    }
                    break;
                case 'city':
                    if (!v || v !== this.cityS) {
                        this.districtS = '';
                    }
                    break;
            }
            const { addForm, counS, provS, cityS, districtS } = this;
            const { counSelected, countrys, provsSelected, provs, citySelected, citys, districtSelected, districts } = addForm.browsers[type];
            const countryStore = addForm.browsers.country;
            const provinceStroe = addForm.browsers.province;
            const cityStore = addForm.browsers.city;
            const districtStore = addForm.browsers.district;

            let  countryStoreIsNotdeFined = typeof(countryStore) != "undefined";
            let  provinceStroeIsNotdeFined = typeof(provinceStroe) != "undefined";
            let  cityStoreIsNotdeFined = typeof(cityStore) != "undefined";
            let  districtIsNotdeFined = typeof(districtStore) != "undefined";


            const coun = countryStoreIsNotdeFined&&(countrys.length ? countrys : countryStore.countrys).find(c => c.id === (counSelected || counS));
            const prov = provinceStroeIsNotdeFined&&(provs.length ? provs : provinceStroe.provs).find(p => p.id === (provsSelected || provS));
            const city = cityStoreIsNotdeFined&&(citys.length ? citys : cityStore.citys).find(ci => ci.id === (citySelected || cityS));
            const district = districtIsNotdeFined&&(districts.length ? districts : districtStore.districts).find(dis => dis.id === (districtSelected || districtS));
           
            const counUrl = `/api/public/browser/data/258`;
            const provinceUrl = `/api/public/browser/data/2222`;
            const cityUrl = `/api/public/browser/data/58`;
            const districtUrl = `/api/public/browser/data/263`;

            if (coun) {
                countryStoreIsNotdeFined&&countryStore.countryClick(counUrl, coun, 258);
                provinceStroeIsNotdeFined&&provinceStroe.countryClick(counUrl, coun, 2222);
                cityStoreIsNotdeFined&&cityStore.countryClick(counUrl, coun, 58);
                districtIsNotdeFined&&districtStore.countryClick(counUrl, coun, 263);
            }

            if (prov) {
                countryStoreIsNotdeFined&&countryStore.provClick(provinceUrl, prov, 258);
                provinceStroeIsNotdeFined&&provinceStroe.provClick(provinceUrl, prov, 2222);
                cityStoreIsNotdeFined&&cityStore.provClick(provinceUrl, prov, 58);
                districtIsNotdeFined&&districtStore.provClick(provinceUrl, prov, 263)
            }

            if(city) {
                countryStoreIsNotdeFined&&countryStore.cityClick(cityUrl, city, 258);
                provinceStroeIsNotdeFined&&provinceStroe.cityClick(provinceUrl, prov, 2222);
                cityStoreIsNotdeFined&&cityStore.cityClick(cityUrl, city, 58);
                districtIsNotdeFined&&districtStore.cityClick(cityUrl, city, 263);
            }

            const setDistrict = (store, type) => {
                store.counSelected = counSelected || (coun && coun.id);
                store.provsSelected = provsSelected || (prov && prov.id);
                store.citySelected = citySelected || (city && city.id);
                store.districtSelected = districtSelected || (district && district.id);
                //countryStoreIsNotdeFined&&countryStore.districtClick(districtUrl, district, type);
               // provinceStroeIsNotdeFined&&provinceStroe.districtClick(districtUrl, district, 2222);
               // cityStoreIsNotdeFined&&cityStore.districtClick(districtUrl, district, 58);
            }

            if(district) {
                // setDistrict(countryStore, 258);
                setDistrict(districtStore, 263)
            }

            window.__setValue = (store) => {
                store.counSelected = counSelected || (coun && coun.id);
                store.provsSelected = provsSelected || (prov && prov.id);
                store.citySelected = citySelected || (city && city.id);
                store.districtSelected = districtSelected || (district && district.id);
                window.__setValue = null;
            };
            this.counS = counSelected || (coun && coun.id);
            this.provS = provsSelected || (prov && prov.id);
            this.cityS = citySelected || (city && city.id);
            this.districtS = districtSelected || (district && district.id);
            let flag = true;
            
            if(!this.counS && !this.provS && !this.cityS && !this.districtS) {
                flag = false;
            }
            countryStoreIsNotdeFined&&coun&&addForm.updateField('country', [{ id: this.counS || (flag ? -1 : '' ), name: coun && coun.name }]);
            provinceStroeIsNotdeFined&&addForm.updateField('province', [{ id: this.provS || (flag ? -1 : ''), name: (prov && prov.name)}]);
            cityStoreIsNotdeFined&&addForm.updateField('city', [{ id: this.cityS || (flag ? -1 : ''), name: (city && city.name) }]);
            districtIsNotdeFined&&addForm.updateField('district', [{ id: this.districtS || (flag ? -1 : ''), name: district && district.name }]);
        }
    }
}